package service

import (
	"fmt"
	"goapp-web-server/app/models"
	"goapp-web-server/app/utils/orm"
)

type CmsArticle struct {
	models.CmsArticle `xorm:"extends"`
	Category          models.CmsCategory `json:"category" xorm:"extends"`
	CommentCount      int32              `json:"comment_count" xorm:"comment_count"`
	ZanCount          int32              `json:"zan_count" xorm:"zan_count"`
}
type CmsArticleService interface {
	GetAll() ([]CmsArticle, error)
	GetByID(id int64) (CmsArticle, error)
	Add(article models.CmsArticle) (id int64, success error)
}

func NewArticleService() CmsArticleService {
	return new(articleService)
}

type articleService struct {
}

// article list
func (s *articleService) GetAll() ([]CmsArticle, error) {
	engine := orm.Engine
	list := make([]CmsArticle, 0)
	err := engine.Table("cms_article").
		Select(`cms_article.*, cms_category.*, 
		(select count(id) from cms_comment where cms_comment.topic_id = cms_article.id) as comment_count, 
		(select count(id) from cms_zan where cms_zan.type_id = cms_article.id) as zan_count`).
		Join("LEFT", "cms_category", "cms_article.category_id = cms_category.id").
		Where("cms_article.deleted_at is NULL").
		Limit(10, 0).
		Find(&list)
	if err != nil {
		fmt.Println("error:", err)
		return nil, err
	}
	return list, nil
}

// get article by id
func (s *articleService) GetByID(id int64) (CmsArticle, error) {
	engine := orm.Engine
	article := CmsArticle{}
	_, err := engine.Table("cms_article").
		Select(`cms_article.*, cms_category.*, 
		(select count(id) from cms_comment where cms_comment.topic_id = cms_article.id) as comment_count, 
		(select count(id) from cms_zan where cms_zan.type_id = cms_article.id) as zan_count`).
		Join("LEFT", "cms_category", "cms_article.category_id = cms_category.id").
		Where("cms_article.deleted_at is NULL AND cms_article.id = ?", id).
		Get(&article)
	fmt.Println(article.Title)
	if err != nil {
		fmt.Println("error:", err)
		return article, err
	}
	return article, nil
}

// add article
func (S *articleService) Add(article models.CmsArticle) (id int64, success error) {
	engine := orm.Engine
	id, err := engine.Insert(&article)
	if err != nil {
		fmt.Println("error:", err)
		return 0, err
	}
	return id, nil
}

// update
func (S *articleService) Update(id int64) (CmsArticle, error) {
	article := CmsArticle{}
	return article, nil
}

// delete
func (S *articleService) Delete(id int64) (CmsArticle, error) {
	article := CmsArticle{}
	return article, nil
}
